package com.slimbloody.warmup;


import com.slimbloody.infra.warmup.WarmUp;
import jdk.nashorn.internal.ir.annotations.Immutable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Import;

import java.util.Map;
import java.util.Set;


@Slf4j
public class WarmUpComponent implements ApplicationContextAware, ApplicationListener<ApplicationStartedEvent> {
  private ApplicationContext applicationContext;
  private WarmUpIgnoreConfiguration ignoreConfiguration;

  public WarmUpComponent(WarmUpIgnoreConfiguration ignoreConfiguration) {
    this.ignoreConfiguration = ignoreConfiguration;
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
  }

  @Override
  public void onApplicationEvent(ApplicationStartedEvent event) {
    Set<String> ignoreSet = ignoreConfiguration.getIgnoreSet();
    Map<String, WarmUp> beans = applicationContext.getBeansOfType(WarmUp.class);

    for (Map.Entry<String, WarmUp> bean : beans.entrySet()) {
      String beanName = bean.getKey();
      if (ignoreSet.contains(beanName)) {
        log.info("warmup skip: {}", beanName);
        continue;
      }

      log.info("warmup: {}", beanName);
      if (!bean.getValue().warm()) {
        log.warn("warmup failed: {}", beanName);
        continue;
      }
    }
  }
}
